package com.niit.agricstore.config;


import com.niit.agricstore.filter.ControllerExceptionFilter;
import com.niit.agricstore.interceptor.CorsInterceptor;
import com.niit.agricstore.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路由
        registry.addMapping("/**")
                // 设置允许跨域请求的域名------------修改此行
                .allowedOriginPatterns("*")
                // 是否允许证书（cookies）
                .allowCredentials(true)
                .allowedHeaders(CorsConfiguration.ALL)
                // 设置允许的方法
                .allowedMethods("*")
                // 跨域允许时间
                .maxAge(3600);
    }
    //注册跨域拦截器
    @Bean
    public CorsInterceptor corsInterceptor() {
        return new CorsInterceptor();
    }
    //注册Token拦截器
    @Bean
    public TokenInterceptor tokenInterceptor(){
        return new TokenInterceptor();
    }
    @Autowired
    private TokenInterceptor tokenInterceptor;
//注册
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(corsInterceptor()) //注册自定义拦截器
                .addPathPatterns("/**"); // 拦截的路径
        registry.addInterceptor(tokenInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login/**",
                        "/home/**",
                        "/user/register",
                        "/pic/**","/**"); //不拦截的路径
    }
}